import React from 'react';
import { Link } from 'react-router';
import { Icon, Button, Row, Col, message, Modal, Input, Select, Form } from 'antd';
import moment from 'moment';
import $ from 'jquery';
import Config from '../../common/config';
import Region from '../../common/region';

const Option = Select.Option;
const FormItem = Form.Item;
const config = new Config;
const token = sessionStorage.getItem('token');

class orderDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      orderId: this.props.params.orderId,
      data: {}, // 订单数据
      province: '', // 默认的省
      provinceList: [], // 省选择
      city: '', // 默认的市
      cityList: [], // 市选择
      area: '', // 默认的区
      areaList: [], // 区选择
      userVisible: false, //会员信息对话框
      userData: {}, //查看的会员信息
    }
    this.changName = this.changName.bind(this);
    this.changPhone = this.changPhone.bind(this);
    this.changMailcode = this.changMailcode.bind(this);
    this.selectProvince = this.selectProvince.bind(this);
    this.selectCity = this.selectCity.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentWillMount() {
    this.getData();
  }

  // 获取订单详情内容
  getData() {
    $.ajax({
      url: `${config.JuseOrder}/orderList/detail`,
      type: 'get',
      headers: {
        'Authorization': 'Bearer ' + token,
      },
      data: {
        orderId: this.state.orderId
      },
      success: (res) => {
        console.log('订单数据', res);
        if (res.code === 200) {
          const order = res.data;
          this.setState({
            data: order,
          });
          if ([1, 2].includes(this.state.data.orderStatus)) {
            const consigneeArea = order.consigneeArea.split(' ');
            const province = consigneeArea[0] || ' ';
            const city = consigneeArea[1] || ' ';
            const area = consigneeArea[2] || ' ';
            this.handleArea(province, city);
            this.props.form.setFieldsValue({
              consigneeName: order.consigneeName,
              consigneePhone: order.consigneePhone,
              consigneeMailcode: order.consigneeMailcode,
              province,
              city,
              area,
              consigneeDetail: order.consigneeDetail,
              buyerMessage: order.buyerMessage,
              remark: order.remark
            });
            this.setState({
              province,
              city,
              area
            });
          }
        }
      }
    });
  }

  // 处理省市区
  handleArea(province, city) {
    const provinceList = Region;
    let cityList = [];
    let areaList = [];
    provinceList.forEach(item => {
      if (item.name === province) {
        cityList = item.child;
      }
    });
    cityList.forEach(item => {
      if (item.name === city) {
        areaList = item.child;
      }
    });
    this.setState({
      provinceList,
      cityList,
      areaList
    });
  }

  // 显示订单状态
  showOrderStatus() {
    const order = this.state.data;
    let text;
    switch (order.orderStatus) {
      case 1:
        text = '等待买家付款';
        break;
      case 2:
        text = '等待卖家发货';
        break;
      case 3:
        text = '待收货';
        break;
      case 5:
        text = '交易成功';
        break;
      case 6:
      case 7:
      case 8:
      case 9:
        text = '交易关闭';
        break;
    }
    return text;
  }

  // 修改收货人
  changName(e) {
    this.setState({
      consigneeName: e.target.value
    });
  }

  // 修改联系方式
  changPhone(e) {
    this.setState({
      consigneePhone: e.target.value
    });
  }

  // 修改邮编
  changMailcode(e) {
    this.setState({
      consigneeMailcode: e.target.value
    });
  }

  // 选择省
  selectProvince(value) {
    const province = value;
    const city = ' ';
    const area = ' ';
    this.setState({
      province,
      city,
      area
    });
    this.props.form.setFieldsValue({
      province,
      city,
      area
    });
    this.handleArea(province, city);
  }

  // 选择市
  selectCity(value) {
    const province = this.state.province;
    const city = value;
    const area = ' ';
    this.setState({
      city,
      area
    });
    this.props.form.setFieldsValue({
      city,
      area
    });
    this.handleArea(province, city);
  }

  // 表单提交
  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      console.log(values);
      if (!err) {
        $.ajax({
          url: `${config.JuseOrder}/orderList/updateReceivingInformation`,
          type: 'post',
          headers: {
            'Authorization': 'Bearer ' + token,
          },
          data: {
            orderId: this.state.data.orderId,
            consigneeName: values.consigneeName,
            consigneePhone: values.consigneePhone,
            consigneeMailcode: values.consigneeMailcode,
            consigneeArea: values.province + ' ' + values.city + ' ' + values.area,
            consigneeDetail: values.consigneeDetail,
            buyerMessage: values.buyerMessage,
            remark: values.remark
          },
          success: (data) => {
            console.log('修改地址', data);
            if (data.code === 200) {
              this.getData();
            } else {
              message.error(data.mes);
            }
          }
        })
      }
    });
  }

  //查看详情
  getUser(order) {
    //获取会员的地址列表
    $.ajax({
      url: `${config.JuseMember}/userManage/userInfo`,
      type: "get",
      data: {
        userId: order.userId
      },
      headers: {
        'Authorization': 'Bearer ' + token,
      },
      success: (data) => {
        console.log('个人信息', data);
        if (data.code === 200) {
          this.setState({
            userVisible: true,
            userData: data.data,
          })
        } else {
          message.error('获取会员的地址列表失败，请返回重新操作', 2);
        }
      }
    });
  }

  // 关闭用户模态框
  closeDetail() {
    this.setState({
      userVisible: false
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
    return (
      <div className='contentBox clearfix'>
        <div style={{ marginBottom: 15, padding: 10 }}>
          <Link className='onlicksty' to='/orderList'>&lt; 返回</Link>
        </div>
        <Row className='detailRow detailRow-as' style={{ margin: '15px 0', borderBottom: '1px solid #dfdfdf' }}>
          <Col span={4}>订单详情</Col>
          <Col span={4}>
            <span>会员账号：</span>
            <a href='javascript:void(0)' onClick={this.getUser.bind(this, this.state.data)}>{this.state.data.userPhone}</a>
          </Col>
          <Col span={4} offset={12}>
            <Button className='member-button-aa' type='primary'><Link to={'/applyOperation/' + this.state.data.orderId}>代客申请操作</Link ></Button>
          </Col>
        </Row>
        <Row className='detailRow detailRow-as' style={{ margin: '15px 0' }}>
          <Col span={4}>
            <span style={{ marginRight: 10 }}>订单编号：</span>
            <span>{this.state.data.orderId}</span>
          </Col>
          <Col span={4}>
            <span style={{ marginRight: 10 }}>支付状态：</span>
            <span>{this.state.data.isAlreadyPay ? '已支付' : '待买家付款'}</span>
          </Col>
          <Col>
            <span>订单状态：</span>
            <span>{this.showOrderStatus()}</span>
          </Col>
        </Row>
        <div>
          <ul className='detaiList detaiList-adc'>
            <li>
              <Col span={6}>商品图片</Col>
              <Col span={5}>商品名称</Col>
              <Col span={5}>商品单价</Col>
              <Col span={4}>商品数量</Col>
              <Col span={4}>小记</Col>
            </li>
            {
              this.state.data.productList && this.state.data.productList.map((item, i) => (
                <li key={i}>
                  <Col span={6}><img src={item.imageUrl + item.listImage} style={{ width: 50, height: 50 }} /></Col>
                  <Col span={5}>{item.productName}</Col>
                  <Col span={5}>{item.marketPrice}</Col>
                  <Col span={4}>{item.number}</Col>
                  <Col span={4}>{(item.marketPrice * item.number).toFixed(2)}</Col>
                </li>
              ))
            }
          </ul>
          {
            this.state.data.patientDetail
              ?
              <ul className='detaiList'>
                <li>
                  <Col span={6}>处方图片</Col>
                  <Col span={5}>姓名</Col>
                  <Col span={5}>身份证号</Col>
                  <Col span={4}>处方状态</Col>
                  <Col span={4}>备注</Col>
                </li>
                <li>
                  <Col span={6}><img src={this.state.data.patientDetail.prescriptionPicture.split(',')[0]} style={{ width: 50, height: 50 }} /></Col>
                  <Col span={5}>{this.state.data.patientDetail.patientName}</Col>
                  <Col span={5}>{this.state.data.patientDetail.patientCardNumber}</Col>
                  <Col span={4}>
                    {
                      this.state.data.prescriptionStutas === 1
                        ?
                        '待审核'
                        :
                        this.state.data.prescriptionStutas === 2
                          ?
                          '审核通过'
                          :
                          '审核不通过'
                    }
                  </Col>
                  <Col span={4}>{this.state.data.prescriptionRemark}</Col>
                </li>
              </ul>
              :
              ''
          }
          {
            ![1, 2].includes(this.state.data.orderStatus)
              ?
              <ul className='detaiList guestInfo'>
                <li>收货人信息</li>
                <li style={{ marginTop: 20 }}>
                  <Col span={4}>
                    <span className='chengge-aad'>收货人：</span>
                    <span>{this.state.data.consigneeName}</span>
                  </Col>
                  <Col span={4} offset={1}>
                    <span className='chengge-aad'>联系方式：</span>
                    <span>{this.state.data.consigneePhone}</span>
                  </Col>
                  <Col span={4} offset={1}>
                    <span className='chengge-aad'>商品邮编：</span>
                    <span>{this.state.data.consigneeMailcode}</span>
                  </Col>
                </li>
                <li>
                  <span className='chengge-aad'>收货地址：</span>
                  {this.state.data.consigneeArea ? this.state.data.consigneeArea.split(' ').join('') + this.state.data.consigneeDetail : ''}
                </li>
                <li>
                  <span className='chengge-aad'>买家留言：</span>
                  {this.state.data.buyerMessage}
                </li>
                <li>
                  <span className='chengge-aad'>客服备注：</span>
                  {this.state.data.remark}
                </li>
              </ul>
              :
              <Form onSubmit={this.handleSubmit}>
                <ul className='detaiList guestInfo'>
                  <li>
                    <span style={{ fontSize: 14, marginRight: 20 }}>收货人信息</span>
                    <Button htmlType='submit'>修改</Button>
                  </li>
                </ul>
                <div style={{ width: '100%', float: 'left' }}>
                  <div className='asdsf-ttt' style={{ paddingLeft: 64 }}>
                    <FormItem label='收货人：' {...formItemLayout} style={{ width: '80%' }}>
                      {getFieldDecorator('consigneeName', {
                        rules: [{
                          required: true, max: 25, message: '请填写正确的收货人姓名',
                        }],
                      })(
                        <Input />
                      )}
                    </FormItem>
                  </div>
                  <div className='asdsf-ttt'>
                    <FormItem label='联系方式：' {...formItemLayout} style={{ width: '80%' }}>
                      {getFieldDecorator('consigneePhone', {
                        rules: [{
                          required: true, pattern: /^(\d{11})$/, message: '请填写正确的手机号码',
                        }],
                      })(
                        <Input />
                      )}
                    </FormItem>
                  </div>
                  <div className='asdsf-ttt'>
                    <FormItem label='商品邮编：' {...formItemLayout} style={{ width: '80%' }}>
                      {getFieldDecorator('consigneeMailcode', {
                        rules: [{
                          required: true, pattern: /^\d{6}$/, message: '邮政编码由6位数字组成'
                        }],
                      })(
                        <Input />
                      )}
                    </FormItem>
                  </div>
                </div>
                <div style={{ width: '100%', float: 'left' }}>
                  <Row>
                    <Col span={2}>
                      <FormItem>
                        <span style={{ textAlign: 'right', display: 'block' }}>收货地址：</span>
                      </FormItem>
                    </Col>
                    <Col span={4}>
                      <FormItem {...formItemLayout} style={{ width: '100%' }}>
                        <Row>
                          <Col span={20}>
                            {getFieldDecorator('province', {
                            })(
                              <Select onChange={this.selectProvince}>
                                {
                                  this.state.provinceList.map((item, index) => {
                                    return (
                                      <Option key={index} value={item.name}>
                                        {item.name}
                                      </Option>
                                    )
                                  })
                                }
                              </Select>
                            )}
                          </Col>
                          <Col span={1} offset={1}>省</Col>
                        </Row>
                      </FormItem>
                    </Col>
                    <Col span={4}>
                      <FormItem {...formItemLayout} style={{ width: '100%' }}>
                        <Row>
                          <Col span={20}>
                            {getFieldDecorator('city', {
                            })(
                              <Select onChange={this.selectCity}>
                                {
                                  this.state.cityList.map((item, index) => {
                                    return (
                                      <Option key={index} value={item.name}>
                                        {item.name}
                                      </Option>
                                    )
                                  })
                                }
                              </Select>
                            )}
                          </Col>
                          <Col span={1} offset={1}>市</Col>
                        </Row>
                      </FormItem>
                    </Col>
                    <Col span={4}>
                      <FormItem {...formItemLayout} style={{ width: '100%' }}>
                        <Row>
                          <Col span={20}>
                            {getFieldDecorator('area', {
                            })(
                              <Select >
                                {
                                  this.state.areaList.map((item, index) => {
                                    return (
                                      <Option key={index} value={item.name}>
                                        {item.name}
                                      </Option>
                                    )
                                  })
                                }
                              </Select>
                            )}
                          </Col>
                          <Col span={1} offset={1}>区</Col>
                        </Row>
                      </FormItem>
                    </Col>
                    <Col span={5}>
                      <FormItem {...formItemLayout}>
                        {getFieldDecorator('consigneeDetail', {
                          rules: [{
                            required: true, message: '请填写详细地址',
                          }],
                        })(
                          <Input style={{ width: 300 }} />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                </div>
                <div style={{ width: '100%', float: 'left', paddingLeft: 5 }}>
                  <div style={{ width: 500 }}>
                    <FormItem {...formItemLayout} label='买家留言：'>
                      {getFieldDecorator('buyerMessage', {
                      })(
                        <Input />
                      )}
                    </FormItem>
                  </div>
                </div>
                <div style={{ width: '100%', float: 'left', paddingLeft: 5 }}>
                  <div style={{ width: 500 }}>
                    <FormItem {...formItemLayout} label='备注：'>
                      {getFieldDecorator('remark', {
                      })(
                        <Input type='textarea' rows={4} />
                      )}
                    </FormItem>
                  </div>
                </div>
              </Form>
          }
        </div>
        <Modal
          title={'查看会员信息'}
          visible={this.state.userVisible}
          onCancel={this.closeDetail.bind(this)}
          width={550}
          footer={null}
        >
          <ul className='user-info clearfix'>
            <li style={{ width: '100%' }}>账&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号：{this.state.userData.phone}</li>
            <li>邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱：{this.state.userData.email}</li>
            <li>手&nbsp;&nbsp;机&nbsp;&nbsp; 号&nbsp;&nbsp;码：{this.state.userData.phone}</li>
            <li>性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别：{this.state.userData.sex == '0' ? '女' : this.state.userData.sex == '1' ? '男' : this.state.userData.sex == '2' ? '保密' : ''}</li>
            <li>注&nbsp;&nbsp;册&nbsp;&nbsp; 日&nbsp;&nbsp;期：{new Date(this.state.userData.createdAt).toLocaleString()}</li>
            <li>出生日期：{this.state.userData.birthday}</li>
            <li>最后登录日期：{new Date(parseInt(this.state.userData.loginTime)).toLocaleString()}</li>
          </ul>
          <div className='user-address'>
            <p>收货地址：</p>
            <ul>
              {
                this.state.userData.address && this.state.userData.address.map((item, index) => {
                  return (
                    <li key={index}>
                      {
                        item.isDefault == '1' && <span className='user-defaultadd'>[默认]</span>
                      }
                      {item.area + ' ' + item.detail + ' ' + item.name + ' ' + item.phone}
                    </li>
                  )
                })
              }
            </ul>
          </div>
        </Modal>
      </div>
    )
  }
}

export default Form.create()(orderDetail);
